package com.example.suyuan.controller;

import com.example.suyuan.entity.User;
import com.example.suyuan.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    // 用户注册
    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody User user) {
        Map<String, Object> response = new HashMap<>();
        try {
            userService.register(user);
            response.put("message", "User registered successfully");
            response.put("status", "success");
        } catch (Exception e) {
            response.put("message", "User registration failed");
            response.put("status", "error");
            response.put("error", e.getMessage());
        }
        return response;
    }

    // 用户登录
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody User user) {
        Map<String, Object> response = new HashMap<>();
        try {
            boolean isValid = userService.login(user);
            if (isValid) {
                response.put("message", "Login successful");
                response.put("status", "success");
            } else {
                response.put("message", "Invalid username or password");
                response.put("status", "error");
            }
        } catch (Exception e) {
            response.put("message", "Login failed");
            response.put("status", "error");
            response.put("error", e.getMessage());
        }
        return response;
    }
}
